<?php
//ini_set('display_errors', TRUE);
//ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Shanghai');
//define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');//设定换行符 cli表示命令行运行php Apache2handler表示在服务器下运行
error_reporting(E_ALL);

/* Include path 
set_include_path(get_include_path() . PATH_SEPARATOR . './Classes/');//设置include查找的目录
// Include PHPExcel 
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';//downloading*/

/** PHPExcel_IOFactory  在classes文件夹下寻找*/

require_once(dirname(__FILE__).'/Classes/PHPExcel/IOFactory.php');
require_once(dirname(__FILE__).'/Classes/PHPExcel/Worksheet/ColumnDimension.php');
require_once(dirname(__FILE__).'/Classes/PHPExcel.php');

//write
$WriteExcel = new PHPExcel();

/*format and properties*/
function setExcel($title="",$subject="",$creator="fym",$modify="fym")
{

		//$WriteExcel=$GLOBALS['WriteExcel'];
		global $WriteExcel;
		
		// Set document properties
		$WriteExcel->getProperties()->setCreator($creator)
							 ->setLastModifiedBy($modify)
							 ->setTitle($title)
							 ->setSubject($subject);
/*
//设置表头格式
	$styleArrayHead = array(
	'font' => array(
			'bold' => true,
		),
	'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
	'borders' => array('outline' => array('style' => PHPExcel_Style_Border::BORDER_MEDIUM,
	'color' => array('argb' => '00000000')
	,),),);

	$WriteExcel->setActiveSheetIndex(0)->getStyle('A2')->applyFromArray($styleArrayHead);
*/
}

function writeOneCell($cell,$value,$digit=false,$center=false)
{
	global $WriteExcel;
	
	$styleArray = array(
	'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_CENTER),//对齐方式
	);

	if($center){//居中对齐
		$styleArray['alignment']['horizontal']=PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
	}
	
	$cur_sheet=$WriteExcel->setActiveSheetIndex(0);
	if(empty($value)){
		$value=' ';
	}
	//设置值
	$cur_sheet->setCellValue($cell,$value);
	
	//设置边框
	$cur_sheet->getStyle($cell)->applyFromArray($styleArray);
	
	//设置数字的显示格式
	if($digit){
		$cur_sheet->getStyle($cell)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
	}
	
	//设置列自动列宽或者设置列宽
	//$cur_sheet->getColumnDimension('Y')->setWidth(100);//setAutoSize(true);
	/*
	//设置行高
	$cur_sheet->getRowDimension(1)->setRowHeight(100);
	*/
}

//保存到Excel
//11号字母9.5 px
//1 width 7px
//要求每一列80%能显示
function saveToExcel($contents,$start_column='B',$columns,$path,$start_row=2)
{
	if(empty($columns) || empty($contents)){
		return;
	}
	global $WriteExcel;
	
	$cur_sheet=$WriteExcel->setActiveSheetIndex(0);
	
	$row=$start_row;
	$columns_width=array();
	
	foreach($contents as $paper_count=>$cont){//每一行
		$col=$start_column;
		
		if($row==$start_row){
			writeOneCell($start_column.$start_row,'序号');//设置序号列
			writeOneCell($start_column.($start_row+1),$paper_count+1,false,true);//下一行设置编号
		}else{
			writeOneCell($start_column.$row,$paper_count+1,false,true);//下一行设置编号
		}
		
		$col++;//第一列留作序号列
		foreach($columns as $col_index)
		{
			if(!empty($col_index)){
				$value=empty($cont[$col_index])?"":$cont[$col_index];
				//统计单元格长度
				if(!empty($value) && $col_index!='摘要')//如果有值
				{	
					$columns_width[$col][]=strlen(@iconv("utf-8","gbk",$value));
					
				}
				
				if($row==$start_row){
					$columns_title_alpah[$col_index]=$col;//字母列与标题列的映射
					writeOneCell($col.$row,$col_index);//设置标题
					
					if($col_index=='检索号' || $col_index='ISSN' || $col_index='ISBN' || $col_index='CN')//设置检索号显示格式
					{
						writeOneCell($col.($row+1),$value,true);//设置值
					}
					else
					{
						writeOneCell($col.($row+1),$value,false);//设置值
					}
				}
				else{
					
					if($col_index=='检索号' || $col_index='ISSN' || $col_index='ISBN' || $col_index='CN')
					writeOneCell($col.$row,$value,true);//设置值
					else
					writeOneCell($col.$row,$value,false);//设置值
				}
				$col++;	
			}
		}
		$row+=($row==$start_row)?2:1; 

	}
	$cur_sheet->getColumnDimension($start_column)->setWidth(5);//设置序号号列宽度
	foreach($columns as $column_title)
	{
		if(empty($column_title))
			continue;
		$col_alpha=$columns_title_alpah[$column_title];//获取字母索引的列
		if(!empty($columns_width[$col_alpha])){
			$cols_wid=$columns_width[$col_alpha];
			sort($cols_wid);//由小到大排序
			
			$col_size=count($cols_wid);//获取本列的非空行数
			
			$col_bytes=$cols_wid[intval(0.8*$col_size)];//取前80%都能见的宽度
		}
		else{
			$col_bytes=0;//此列为空
		}
		$col_title=@iconv("utf-8","gbk",$column_title);
		$title_len=strlen($col_title);
		if($col_bytes<$title_len){//列的内容不小于列标
			$col_bytes = $title_len;
		}
		$col_bytes=$col_bytes>100?100:$col_bytes;
		if($column_title=='期刊会议名')//因为期刊会议名多半是英文，所以需要调小宽度
		{
			$pixs_per_char=1;
		}
		else{
			$level=array(1.3,1.2,1.1,1.05);//越小倍数越大 1 
			$l_index=($col_bytes-1)/4;
			$l_index=$l_index>3?3:$l_index;
			$pixs_per_char=$level[$l_index];
		}
		$col_width=intval($col_bytes*$pixs_per_char);
		$col_width=($col_width<=2)?($col_width+2):($col_width+1);//因为设置的列宽不一定对
		$cur_sheet->getColumnDimension($col_alpha)->setWidth($col_width);//设置列宽度
		
		/*
			echo "name:".$column_title." bytes:".$col_bytes." px:".$pixs_per_char." Width:".$col_width.EOL;
		var_export($cols_wid);
		echo EOL.EOL;
		*/
	}
	$objWriter = PHPExcel_IOFactory::createWriter($WriteExcel, 'Excel5');//还可以是Excel2007 但是保存的时候记得改后缀
	//$name=dirname(__FILE__)."/searchResult/result.xls";//file name
	//$name=dirname(__FILE__)."/../searchResult/result.xls";
	$objWriter->save($path);//str_replace('.php', '.xlsx', __FILE__)
}

   //echo "<pre>".new ReflectionClass('PHPExcel_Worksheet_ColumnDimension')."</pre>"; //如果想获取类的信息，使用reflectionClass类
	
?>